<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Model\CollectAccount;
use App\Model\Order;
use App\Model\TradeLog;
use App\Model\WithdrawLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * 财务管理
 */
class FinanceController extends Controller
{

    /**
     * 初始化控制器
     */
    public function __construct()
    {

    }

    /**
     * 财务映射
     */
    public function finance_mapping()
    {
        // 是否
        $is = [1 => '是', 2 => '否'];
        // 订单状态
        $order_status = (new Order())->getStatusList();
        // 交易状态
        $trade_status = (new TradeLog())->getStatusList();
        // 提现状态
        $withdraw_status = (new WithdrawLog())->getStatusList();
        $this->success(['is' => $is, 'order_status' => $order_status, 'trade_status' => $trade_status, 'withdraw_status' => $withdraw_status]);
    }

    /**
     * 收款账户选择
     */
    public function collect_account_select()
    {
        $list = (new CollectAccount())->orderBy('id', 'desc')->get(['id', 'account_name'])->toArray();
        $this->success(array_column($list,'account_name','id'));
    }

    /**
     * 收款账户列表
     */
    public function collect_account_list(Request $request)
    {
        // 获取参数
        $params = $request->all();
        // 设置对象
        $model = (new CollectAccount());
        // id
        if (isset($params['account_id']) && $params['account_id']) {
            $model = $model->where('id', $params['account_id']);
        }
        // 开户行
        if (isset($params['bank_id']) && $params['bank_id']) {
            $model = $model->where('bank_id', $params['bank_id']);
        }
        // 支行
        if (isset($params['sub_branch']) && $params['sub_branch']) {
            $model = $model->where('sub_branch', 'like', '%' . $params['sub_branch'] . '%');
        }
        // 账户名
        if (isset($params['account_name']) && $params['account_name']) {
            $model = $model->where('account_name', 'like', '%' . $params['account_name'] . '%');
        }
        // 卡号
        if (isset($params['card_number']) && $params['card_number']) {
            $model = $model->where('card_number', 'like', '%' . $params['card_number'] . '%');
        }
        // 是否主账号
        if (isset($params['is_main']) && $params['is_main']) {
            $model = $model->where('is_main', $params['is_main']);
        }
        // 创建时间
        if (!empty($params['start_createtime']) && !empty($params['end_createtime'])) {
            $model = $model->whereBetween('createtime', [$params['start_createtime'], $params['end_createtime']]);
        }
        // 修改时间
        if (!empty($params['start_updatetime']) && !empty($params['end_updatetime'])) {
            $model = $model->whereBetween('updatetime', [$params['start_updatetime'], $params['end_updatetime']]);
        }
        // 获取条数
        $pageSize = isset($params['pageSize']) && $params['pageSize'] ? $params['pageSize'] : 10;
        $total = $model->count();
        $list = $model->orderBy('id', 'desc')
            ->take($pageSize)
            ->get(['id as account_id', 'bank_id', 'sub_branch', 'account_name', 'card_number', 'is_main', 'createtime', 'updatetime'])
            ->toArray();
        $this->success(['total_count' => $total, 'total_page' => ceil($total / $pageSize), 'list' => $list]);
    }

    /**
     * 添加收款账户
     */
    public function add_collect_account(Request $request)
    {
        // 获取参数
        $only = ['bank_id', 'sub_branch', 'account_name', 'card_number', 'is_main'];
        $params = $request->only($only);
        if ($params) {
            // 规则验证
            $validate = (new \App\Validate\Admin\CollectAccount());
            if (!$validate->check($params, [], [], 'add_collect_account')) {
                $this->error($validate->getError());
            }
            DB::beginTransaction();
            try {
                $model = (new CollectAccount());
                if ($model->count() >= 5) {
                    throw new \Exception('收款账户不超过5个');
                }
                if ($params['is_main'] != 1 && !$model->where('is_main', 1)->first()) {
                    throw new \Exception('请设置主账户');
                }
                if ($params['is_main'] == 1) {
                    $model->where('is_main', 1)->update(['is_main' => 2]);
                }
                foreach ($params as $key => $val) {
                    if (isset($val)) {
                        $model->$key = $val;
                    }
                }
                $result = $model->save();
                if ($result !== false) {
                    DB::commit();
                } else {
                    throw new \Exception('操作失败');
                }
            } catch (\Exception $exception) {
                DB::rollBack();
                $this->error($exception->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error('未插入任何行');
            }
        }
        $this->error('参数不能为空');
    }

    /**
     * 收款账户详情
     */
    public function collect_account_details(Request $request)
    {
        // 获取参数
        $ids = $request->input('account_id');
        $row = (new CollectAccount())->where('id', $ids)->first();
        if (!$row) {
            $this->error('记录未找到');
        }
        $this->success($row);
    }

    /**
     * 编辑收款账户
     */
    public function edit_collect_account(Request $request)
    {
        // 获取参数
        $only = ['account_id', 'bank_id', 'sub_branch', 'account_name', 'card_number', 'is_main'];
        $params = $request->only($only);
        if ($params) {
            // 规则验证
            $validate = (new \App\Validate\Admin\CollectAccount());
            if (!$validate->check($params, [], [], 'edit_collect_account')) {
                $this->error($validate->getError());
            }
            DB::beginTransaction();
            try {
                $model = (new CollectAccount());
                if ($params['is_main'] != 1 && !$model->where('is_main', 1)->first()) {
                    throw new \Exception('请设置主账户');
                }
                if ($params['is_main'] == 1) {
                    $model->where('is_main', 1)->update(['is_main' => 2]);
                }
                $collectAccount = $model::find($params['account_id']);
                unset($params['account_id']);
                foreach ($params as $key => $val) {
                    if (isset($val)) {
                        $collectAccount->$key = $val;
                    }
                }
                $result = $collectAccount->save();
                if ($result !== false) {
                    Db::commit();
                } else {
                    throw new \Exception('操作失败');
                }
            } catch (\Exception $exception) {
                DB::rollBack();
                $this->error($exception->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error('未更新任何行');
            }
        }
        $this->error('参数不能为空');
    }

    /**
     * 删除收款账户
     */
    public function del_collect_account(Request $request)
    {
        // 获取参数
        $ids = $request->input('account_id');
        if ($ids) {
            $count = 0;
            DB::beginTransaction();
            try {
                $model = (new CollectAccount());
                $list = $model::find(explode(',', $ids));
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (\Exception $exception) {
                DB::rollBack();
                $this->error($exception->getMessage());
            }
            if ($count) {
                $this->success($count);
            } else {
                $this->error(__('未删除任何行'));
            }
        }
        $this->error('参数不能为空');
    }

    /**
     * 批量收款账户
     */
    public function multi_collect_account(Request $request)
    {
        // 获取参数
        $ids = $request->input('account_id');
        $field_key = $request->input('field_key');
        $field_val = $request->input('field_val');
        if ($ids && $field_key && $field_val) {
            if (Schema::hasColumn('collect_account', $field_key)) {
                $count = 0;
                DB::beginTransaction();
                try {
                    $model = (new CollectAccount());
                    if ($field_key == 'is_main' && $field_val == 1) {
                        $model->where('is_main', 1)->update(['is_main' => 2]);
                    }
                    $list = $model::find(explode(',', $ids));
                    foreach ($list as $k => $v) {
                        $v->$field_key = $field_val;
                        $count += $v->save();
                    }
                    Db::commit();
                } catch (\Exception $exception) {
                    DB::rollBack();
                    $this->error($exception->getMessage());
                }
                if ($count) {
                    $this->success($count);
                } else {
                    $this->error(__('未更新任何行'));
                }
            } else {
                $this->error('字段不存在');
            }
        }
        $this->error('参数不能为空');
    }

    /**
     * 收款账户银行
     */
    public function collect_account_bank()
    {

        $this->success([1 => '中国银行', 2 => '中国建设银行', 3 => '中国工商银行', 4 => '中国农业银行']);
    }

    /**
     * 财务统计
     */
    public function finance_total()
    {
        // 可提现金额
        $can_withdraw_price = bcdiv((new TradeLog())->where('status', 2)->sum('supply_price'), 100, 2);
        // 冻结金额
        $frozen_price = bcdiv((new TradeLog())->where('status', 1)->sum('supply_price'), 100, 2);
        // 已提现金额
        $already_withdraw_price = bcdiv((new WithdrawLog())->where('status', 1)->sum('withdraw_price'), 100, 2);
        // 累计金额
        $all_price = bcadd(bcadd($can_withdraw_price, $frozen_price, 2), $already_withdraw_price, 2);
        $this->success(compact('can_withdraw_price', 'frozen_price', 'already_withdraw_price', 'all_price'));
    }

    /**
     * 提现
     */
    public function withdraw()
    {

    }

    /**
     * 交易明细列表
     */
    public function trade_log_list(Request $request)
    {
        // 获取参数
        $params = $request->all();
        // 设置对象
        $model = (new TradeLog());
        // id
        if (isset($params['log_id']) && $params['log_id']) {
            $model = $model->where('id', $params['log_id']);
        }
        // 状态
        if (isset($params['status']) && $params['status']) {
            $model = $model->where('status', $params['status']);
        }
        // 创建时间
        if (!empty($params['start_createtime']) && !empty($params['end_createtime'])) {
            $model = $model->whereBetween('createtime', [$params['start_createtime'], $params['end_createtime']]);
        }
        // 获取条数
        $pageSize = isset($params['pageSize']) && $params['pageSize'] ? $params['pageSize'] : 10;
        $total = $model
            ->with(['order', 'orderGoods'])
            ->whereHas('order', function ($query) use ($params) {
                // 订单编号
                if (isset($params['order_sn']) && $params['order_sn']) {
                    $query->where('order_sn', 'like', '%' . $params['order_sn'] . '%');
                }
                // 订单状态
                if (isset($params['order_status']) && $params['order_status']) {
                    $query->where('status', $params['order_status']);
                }
            })
            ->whereHas('orderGoods', function ($query) use ($params) {
                // 商品编码
                if (isset($params['goods_sn']) && $params['goods_sn']) {
                    $query->where('goods_sn', 'like', '%' . $params['goods_sn'] . '%');
                }
                // 规格编码
                if (isset($params['sku_sn']) && $params['sku_sn']) {
                    $query->where('sku_sn', 'like', '%' . $params['sku_sn'] . '%');
                }
                // 条形码
                if (isset($params['bar_code']) && $params['bar_code']) {
                    $query->where('bar_code', 'like', '%' . $params['bar_code'] . '%');
                }
                // 商品标题
                if (isset($params['goods_title']) && $params['goods_title']) {
                    $query->where('goods_title', 'like', '%' . $params['goods_title'] . '%');
                }
            })
            ->count();
        $list = $model
            ->with(['order', 'orderGoods'])
            ->whereHas('order', function ($query) use ($params) {
                // 订单编号
                if (isset($params['order_sn']) && $params['order_sn']) {
                    $query->where('order_sn', 'like', '%' . $params['order_sn'] . '%');
                }
                // 订单状态
                if (isset($params['order_status']) && $params['order_status']) {
                    $query->where('status', $params['order_status']);
                }
            })
            ->whereHas('orderGoods', function ($query) use ($params) {
                // 商品编码
                if (isset($params['goods_sn']) && $params['goods_sn']) {
                    $query->where('goods_sn', 'like', '%' . $params['goods_sn'] . '%');
                }
                // 规格编码
                if (isset($params['sku_sn']) && $params['sku_sn']) {
                    $query->where('sku_sn', 'like', '%' . $params['sku_sn'] . '%');
                }
                // 条形码
                if (isset($params['bar_code']) && $params['bar_code']) {
                    $query->where('bar_code', 'like', '%' . $params['bar_code'] . '%');
                }
                // 商品标题
                if (isset($params['goods_title']) && $params['goods_title']) {
                    $query->where('goods_title', 'like', '%' . $params['goods_title'] . '%');
                }
            })
            ->orderBy('id', 'desc')
            ->take($pageSize)
            ->get(['id as log_id', 'order_id', 'order_goods_id', 'supply_price', 'status', 'createtime'])
            ->toArray();
        foreach ($list as &$val) {
            if (!empty($val['order_goods'])) {
                $val['order_goods']['goods_image'] = replace_imgs_url($val['order_goods']['goods_image']);
            }
        }
        $this->success(['total_count' => $total, 'total_page' => ceil($total / $pageSize), 'list' => $list]);
    }

    /**
     * 提现记录列表
     */
    public function withdraw_log_list(Request $request)
    {
        // 获取参数
        $params = $request->all();
        // 设置对象
        $model = (new WithdrawLog());
        // id
        if (isset($params['log_id']) && $params['log_id']) {
            $model = $model->where('id', $params['log_id']);
        }
        // 提现单号
        if (isset($params['withdraw_sn']) && $params['withdraw_sn']) {
            $model = $model->where('withdraw_sn', 'like', '%' . $params['withdraw_sn'] . '%');
        }
        // 状态
        if (isset($params['status']) && $params['status']) {
            $model = $model->where('status', $params['status']);
        }
        // 创建时间
        if (!empty($params['start_createtime']) && !empty($params['end_createtime'])) {
            $model = $model->whereBetween('createtime', [$params['start_createtime'], $params['end_createtime']]);
        }
        // 获取条数
        $pageSize = isset($params['pageSize']) && $params['pageSize'] ? $params['pageSize'] : 10;
        $total = $model
            ->with(['collectAccount'])
            ->whereHas('collectAccount', function ($query) use ($params) {
                // 账户名
                if (isset($params['account_name']) && $params['account_name']) {
                    $query->where('account_name', 'like', '%' . $params['account_name'] . '%');
                }
            })
            ->count();
        $list = $model
            ->with(['collectAccount'])
            ->whereHas('collectAccount', function ($query) use ($params) {
                // 账户名
                if (isset($params['account_name']) && $params['account_name']) {
                    $query->where('account_name', 'like', '%' . $params['account_name'] . '%');
                }
            })
            ->orderBy('id', 'desc')
            ->take($pageSize)
            ->get(['id as log_id', 'account_id', 'withdraw_sn', 'withdraw_price', 'status', 'createtime'])
            ->toArray();
        $this->success(['total_count' => $total, 'total_page' => ceil($total / $pageSize), 'list' => $list]);
    }
}
